<!-- 二级分类 -->
<template>
  <div class="sub-category">
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />

      <!-- 商品筛选 -->
      <SubFilter @filter-change="changeFilter" />

      <!-- 商品分类 -->
      <div class="goods-list">
        <!-- 排序 -->
        <SubSort @sort-change="changeSort" />
        <!-- 列表 -->
        <ul>
          <li v-for="goods in goodsList" :key="goods.id">
            <GoodsItem :goods="goods" />
          </li>
        </ul>

        <!-- 加载 -->
        <InfiniteLoading :loading="loading" :finished="finished" @infinite="getList" />
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, watch } from 'vue'
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import GoodsItem from './components/goods-item.vue'
import { findSubCategoryGoods } from "@/api/category"
import { useRoute } from 'vue-router'

export default defineComponent({
  name: "SubCategory",
  setup() {
    const route = useRoute()
    // 查询参数
    let reqParams = {
      page: 1,
      pageSize: 20
    }
    const loading = ref(false)
    const finished = ref(false)
    const goodsList = ref([])
    const getList = () => {
      loading.value = true
      reqParams.categoryId = route.params.id
      findSubCategoryGoods(reqParams).then(({ result }) => {
        if (result.items.length) {
          /* 接口每次返回的都是相同数据, 随机打乱一下 */
          result.items.sort(function () {
            return (0.5 - Math.random());
          });
          goodsList.value.push(...result.items)
          reqParams.page++
        } else {
          // 加载完毕
          finished.value = true
        }
        // 请求结束
        loading.value = false
      })
    }

    watch(() => route.params.id, (newVal) => {
      if (newVal && route.path === ('/category/sub/' + newVal)) {
        goodsList.value = []
        reqParams = {
          page: 1,
          pageSize: 20
        }
        finished.value = false
      }
    })


    const changeFilter = (filterParams) => {
      reqParams = Object.assign(reqParams, filterParams)
      reqParams.page = 1
      goodsList.value = []
      finished.value = false
    }

    const changeSort = (sortParams) => {
      reqParams = Object.assign(reqParams, sortParams)
      reqParams.page = 1
      goodsList.value = []
      finished.value = false
    }

    return {
      getList,
      finished,
      loading,
      goodsList,
      changeFilter,
      changeSort
    }
  },
  components: { SubBread, SubFilter, SubSort, GoodsItem }
})
</script>

<style lang="less" scoped>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>